package com.iwhalecloud.bss.kite.cucc.web.controller.attr;

import java.util.List;
import java.util.Optional;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IUnicomRegionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.AreaCode;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.AreaInquiry;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.StdAddrQry;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegion;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegionQry;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.ExecAddressDTO;
import com.iwhalecloud.bss.kite.cucc.common.util.KiteAssert;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.change.SceneModifyRecord;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.ztesoft.bss.common.util.ContextUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @ClassName : UnicomRegionController
 * @Description : 联通集团区域
 * @Author : xie.zhengjun
 * @Date : 2020/9/18 17:47
 */
@Api(tags = {"/unicomRegion - 联通集团区域"})
@RestController
@RequestMapping("/unicomRegion")
public class UnicomRegionController {
    @Resource
    private IUnicomRegionService unicomRegionService;

    @Resource
    private IQuerySceneInstService querySceneInstService;

    @ApiOperation(value = "获取子区域", notes = "获取子区域")
    @ApiImplicitParams({@ApiImplicitParam(name = "regionCode", value = "区域编码")})
    @GetMapping("/subRegion")
    public DataResult<List<UnicomRegion>> listSubRegion(@RequestParam(required = false) String regionCode) {
        return ErrorConsts.SUCCESS.getResult(unicomRegionService.listSubRegion(regionCode));
    }

    @ApiOperation(value = "获取子区域（多个区域编码）", notes = "获取子区域（多个区域编码）")
    @ApiImplicitParams({@ApiImplicitParam(name = "regionCode", value = "多个区域编码英文逗号隔开")})
    @GetMapping("/subRegionMulti")
    public DataResult<List<List<UnicomRegion>>> listSubRegionMulti(@RequestParam(required = false) String regionCode) {
        return ErrorConsts.SUCCESS.getResult(unicomRegionService.listSubRegionMulti(regionCode));
    }

    @ApiOperation(value = "获取区域详情", notes = "获取区域详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "regionCode", value = "区域编码", required = true)})
    @GetMapping
    public DataResult<UnicomRegion> getRegion(@RequestParam String regionCode) {
        return ErrorConsts.SUCCESS.getResult(unicomRegionService.getRegion(regionCode));
    }

    @ApiOperation(value = "查询装机地址", notes = "查询装机地址")
    @PostMapping("/addr")
    public DataResult<List<ExecAddressDTO>> queryStdAddr(@RequestBody StdAddrQry stdAddrQry) {
        String custId = KiteWebContext.getContext().getCustId();
        KiteAssert.notBlank(custId, ErrorConsts.CUST_ID_NOT_EMPTY);
        return ErrorConsts.SUCCESS.getResult(unicomRegionService.queryStdAddr(stdAddrQry, custId));
    }

    /**
     * 应用系统区域查询服务(国内)
     * 根据上级区域编码查询省市县子区域信息，条件为空，默认查所有省
     */
    @ApiOperation(value = "政企运营平台接口查询子区域(国内)", notes = "政企运营平台接口查询子区域(国内)")
    @PostMapping("/innerSubRegionFromPlatform")
    public DataResult<List<UnicomRegion>> innerSubRegionFromPlatform(@RequestBody(required = false) UnicomRegionQry unicomRegionQry) {
        List<UnicomRegion> list = unicomRegionService.innerSubRegionFromPlatform(unicomRegionQry);
        return ErrorConsts.SUCCESS.getResult(list);
    }

    /**
     * 应用系统区域查询服务(国内+国际)
     * 根据上级区域编码查询省市县子区域信息，条件为空，默认查所有省
     */
    @ApiOperation(value = "政企运营平台接口查询子区域(国内+国际)", notes = "政企运营平台接口查询子区域(国内+国际)")
    @PostMapping("/subRegionFromPlatform")
    public DataResult<List<UnicomRegion>> subRegionFromPlatform(@RequestBody(required = false) UnicomRegionQry unicomRegionQry) {
        List<UnicomRegion> list = unicomRegionService.subRegionFromPlatform(unicomRegionQry);
        return ErrorConsts.SUCCESS.getResult(list);
    }

    /**
     * 应用系统区域查询服务(国内+国际)
     * 根据上级区域编码查询省市县子区域信息（多个区域编码），条件为空，默认查所有省
     */
    @ApiOperation(value = "政企运营平台接口查询子区域(国内+国际)（多个区域编码）", notes = "政企运营平台接口查询子区域(国内+国际)（多个区域编码）")
    @PostMapping("/subRegionMultiFromPlatform")
    public DataResult<List<List<UnicomRegion>>> subRegionMultiFromPlatform(@RequestBody(required = false) List<UnicomRegionQry> unicomRegionQryList) {
        if (KiteListUtils.isNotEmpty(unicomRegionQryList)) {
            String prodInstId = unicomRegionQryList.get(0).getProdInstId();
            if(KiteStringUtils.isNotEmpty(prodInstId)) {
                KiteProdInst prodInst = querySceneInstService.getProdInst(KiteWebContext.getContext().getCustId(), prodInstId);
                String productId = prodInst.getSpecId();
                String sceneInstId = Optional.ofNullable(prodInst.getModifyRecords().stream().findFirst().orElse(null)).map(SceneModifyRecord::getSceneInstId).orElse(KiteWebContext.getContext().getCurrentSceneInstId());
                unicomRegionQryList.forEach(unicomRegionQry -> {
                    unicomRegionQry.setProductId(productId);
                    unicomRegionQry.setSceneInstId(sceneInstId);
                });
            }
        }
        // 批量受理单个修改页面，选择装机地址只展示当前省
        List<List<UnicomRegion>> regionList = unicomRegionService.subRegionMultiFromPlatform(unicomRegionQryList);
        if (KiteStringUtils.isNotEmpty(KiteWebContext.getContext().getCurrentSceneInstId())
            && KiteStringUtils.isNotEmpty(querySceneInstService
                .getExtParameterValue(KiteWebContext.getContext().getCurrentSceneInstId(), "curOfferInstId"))
            && (KiteListUtils.isEmpty(unicomRegionQryList)
                || KiteStringUtils.isEmpty(unicomRegionQryList.get(0).getParentAreaCode()))
            && KiteListUtils.isNotEmpty(regionList)) {
            List<UnicomRegion> regions = regionList.get(0);
            regions.removeIf(region -> !KiteStringUtils.equals(region.getRegionCode(),
                ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr()));
        }
        return ErrorConsts.SUCCESS.getResult(regionList);
    }

    /**
     * 应用系统区域查询服务(国内+国际)
     * 根据上级区域编码查询省市县子区域信息（多个区域编码）
     * 翻译组件默认值，传参为逗号分隔字符串，依次为省,市,县
     */
    @ApiOperation(value = "政企运营平台接口查询子区域(国内+国际)（多个区域编码），参数为逗号分隔的省市县编码", notes = "政企运营平台接口查询子区域(国内+国际)（多个区域编码），参数为逗号分隔的省市县编码")
    @ApiImplicitParams({@ApiImplicitParam(name = "regionCode", value = "依次省市县编码英文逗号隔开")})
    @GetMapping("/subRegionMultiFromPlatformByRegionCode")
    public DataResult<List<List<UnicomRegion>>> subRegionMultiFromPlatformByRegionCode(@RequestParam(required = false) String regionCode) {
        return ErrorConsts.SUCCESS.getResult(unicomRegionService.subRegionMultiFromPlatformByRegionCode(regionCode));
    }

    /**
     * 应用系统区域查询服务(国际)
     * 根据上级区域编码查询省市县子区域信息，条件为空，默认查所有省
     */
    @ApiOperation(value = "政企运营平台接口查询子区域(国际)", notes = "政企运营平台接口查询子区域(国际)")
    @PostMapping("/interSubRegionFromPlatform")
    public DataResult<List<UnicomRegion>> interSubRegionFromPlatform(@RequestBody(required = false) UnicomRegionQry unicomRegionQry) {
        List<UnicomRegion> list = unicomRegionService.interSubRegionFromPlatform(unicomRegionQry);
        return ErrorConsts.SUCCESS.getResult(list);
    }

    /**
     * 3.4.行政区域编码转换服务
     */
    @ApiOperation(value = "3.4.行政区域编码转换服务", notes = "3.4.行政区域编码转换服务")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "code", value = "行政区域编码"),
        @ApiImplicitParam(name = "gradeId", value = "行政区域级别（1：省份；2：地市；3：区县）")
    })
    @PostMapping("/regionTransform")
    public DataResult<AreaCode> regionTransform(@RequestBody AreaInquiry areaInquiry) {
        return ErrorConsts.SUCCESS.getResult(unicomRegionService.regionTransform(areaInquiry));
    }

    @ApiOperation(value = "系统区域查询服务")
    @PostMapping("/getUnicomRegions")
    public DataResult<List<UnicomRegion>> getUnicomRegions(@RequestParam String regionCode) {
        List<UnicomRegion> list = unicomRegionService.getUnicomRegions(regionCode);
        return ErrorConsts.SUCCESS.getResult(list);
    }

    @ApiOperation(value = "省份区域查询")
    @GetMapping("/getProvinceRegion")
    public DataResult<UnicomRegion> getProvinceRegion(@RequestParam(required = false) String regionCode) {
        if (KiteStringUtils.isEmpty(regionCode)) {
            regionCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        }
        return ErrorConsts.SUCCESS.getResult(unicomRegionService.getRegion(regionCode));
    }
}
